package com.lhj.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author lhj
 * @Classname AuthenticatorTest
 * @Description
 * @Date 2021/1/25 16:02
 * @Version V1.0
 */
public class AuthenticatorTest {


    @Test
    public void testAllSuccessfulStrategyWithSuccess() {
        login("classpath:shiro-authenticator-all-success.ini");
        Subject subject = SecurityUtils.getSubject();
        //得到一个身份集合，其包含了<code>Realm</code>验证成功的身份信息
        PrincipalCollection principalCollection = subject.getPrincipals();
        Assert.assertEquals(2, principalCollection.asList().size());
    }


    @Test
    public void testAllSuccessfulStrategyWithFail() {
        login("classpath:shiro-authenticator-all-fail.ini");
        Subject subject = SecurityUtils.getSubject();
        //得到一个身份集合，其包含了<code>Realm</code>验证成功的身份信息
        PrincipalCollection principalCollection = subject.getPrincipals();

        System.out.println("验证信息列表：" + principalCollection.asList().size());
        Assert.assertEquals(2, principalCollection.asList().size());
    }


    private static void login(String configFile) {
        //1、获取<code>SecurityManager</code>工厂，此处使用<code>Ini</code>配置文件初始化<code>SecurityManager</code>
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory(configFile);
        //2、得到<code>SecurityManager</code>实例 并绑定给<code>SecurityUtils</code>
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //3、得到<code>Subject</code>及创建用户名/密码身份验证<code>Token</code>（即用户身份/凭证）
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
        subject.login(token);
    }

}
